<!-- pages/myDevices/myDevices.vue -->
<template>
  <view class="page">
	
	<!-- 设备列表区域 -->
	<scroll-view class="device-list" scroll-y refresher-enabled 
		:refresher-triggered="refreshing" 
		@refresherrefresh="onRefresh"
		@refresherrestore="onRestore"
		@refresherabort="onAbort"
	>
		<view v-if="deviceList.length === 0" class="empty-state">
			<image class="empty-image" :src="emptyStateImage" mode="aspectFit" />
			<!--<text class="empty-text">暂无设备，点击右下角添加设备</text>-->
		</view>
		<view v-else class="device-grid">
			<view
			v-for="device in deviceList"
			:key="device.id"
			class="device-card"
			:style="{ cursor: device.bindStatus ? 'pointer' : 'default', opacity: device.bindStatus ? 1 : 1 }"
			>
				<image mode="aspectFit" class="device-image" @click="navigateToDetail(device.deviceId)"
				      v-if="device.deviceType === 1" 
				      :src="device.onlineStatus === 1 ? OnlineImg : OfflineImg"
				></image>
				<image mode="aspectFit" class="device-image" @click="navigateToDetail(device.deviceId)"
				      v-else 
				      :src="device.onlineStatus === 1 ? OnlineImg : OfflineImg"
				></image>
				
				
				<view class="device-info">
					<text class="device-name" id= {{device.deviceId}}>{{ device.deviceName }} </text>
					 
					<view class="device-status">
							<!--<image :src="getBatteryIcon(device.voltagePercentage)" mode="widthFix" class="BatteryIcon"></image>-->
						<BatteryIndicator :level="device.voltagePercentage" />
						
						<!-- 在线/离线状态 -->
						<view class="status-item">
							<view :class="['status-dot', device.onlineStatus ? 'online' : 'offline']"></view>
							<text class="status-text">{{ device.onlineStatus ? '在线' : '离线' }}</text>
						</view>
						<uni-icons v-if="device.bindStatus" type="checkmark-filled" size="16" color="#4CD964"/>		
						<uni-icons type="trash"size="20"color="#FF3B30" @click="showPopup(device.deviceId)"/>
					</view>
				</view>		
			</view>
		</view>
	</scroll-view>	
    <!-- 底部导航栏 -->
    <view class="tab-bar">
      <view class="tab-item" @click="switchTab('myDevices')">
		<image src = "/static/icons/device.png" class="device"></image>
    	<text class="tab-text,active">设备</text>
      </view>
      <view class="tab-item" @click="switchTab('userInfo')">
    	<image src = "/static/icons/user.png" class="user"></image>
    	<text  class="tab-text">我的</text>
      </view>
    </view>
    <!-- 添加设备按钮 -->
	<view v-if="deviceList.length === 0">
		<view class="image-container" >
			<!--<image src="/static/loading_background.png" class="backgroound"></image>-->
			<view class="text-overlay">点击这里，<br/>添加你的蓝豆包AI朋友!</view>
			<image src="/static/icons/jiantou.png" class="jiantou"></image>
		</view>
		
	</view>
    <!--<view class="add-button" @click="showAddOptions">-->
	<view class="add-button" @click="addDevice">
      <uni-icons type="plus" color="#FFFFFF" size="24"/>
    </view>
    <!-- 添加设备选项弹出层 -->
    <uni-popup ref="addPopup" type="bottom">
      <view class="popup-content">
        <view class="popup-title">设备管理</view>
        <view class="popup-option" @click="addDevice">
          <uni-icons type="plusempty" size="24" color="#007AFF"/>
          <text class="option-text">设备配网</text>
        </view>
		<!--<view class="popup-option" @click="deviceRegister">
		  <uni-icons type="link" size="24" color="#007AFF"/>
		  <text class="option-text">设备绑定</text>
		</view>
        <view class="popup-option" @click="scanCode">
          <uni-icons type="scan" size="24" color="#007AFF"/>
          <text class="option-text">扫一扫</text>
        </view>-->
        <view class="popup-cancel" @click="hideAddOptions">取消</view>
      </view>
    </uni-popup>
    <!-- 删除确认弹框
	<uni-popup ref="popup" type="center" :mask-click="true" mask-background-color="rgba(0,0,0,0)" @change="popupChange">
		<view class="loading-box">
			<view class="title">提示</view>
			<view class="desc">确定要解绑设备{{SelectDeviceName}}吗？</view>
		    
		    <view class="button-group">
		      <button class="btn cancel-btn" @click="hidePopup">取消 </button>
		      <button class="btn confirm-btn" @click="confirmDeletion">确认</button>
		    </view>
		</view>
	</uni-popup>-->
	
	
	<!--设备删除弹窗-->
	<view >
	    <custom-popup
	      ref="popupRef"
	      title="提示"
	      :buttons="buttons"
	      @close="handleClose"
	      @maskClick="handleMaskClick"
	      @buttonClick="handleButtonClick"
	    >
		<text>确定要注销设备吗?</text>
	    </custom-popup>
	</view>
  
  </view>
</template>

<script lang="ts" setup>
import { ref,onMounted} from 'vue';
import { getDeviceList,deleteDevice } from '../../app/device';
import {onShow} from '@dcloudio/uni-app';
import { deviceOnlineImg,deviceOfflineImg } from '../../config/index';
import type { UniPopup } from '@dcloudio/uni-ui';
import CustomPopup from '../../components/custom-popup.vue'
import BatteryIndicator from '../../components/BatteryIndicator.vue'
//自定义popup弹框
interface ButtonItem {
	text: string
	type?: 'primary' | 'warn' | 'default'
	action?: () => void | Promise<void>
}
const popupRef = ref<InstanceType<typeof CustomPopup> | null>(null)
// const popupRef = ref<InstanceType<typeof UniPopup> | null>(null);
const popup = ref<InstanceType<typeof UniPopup>>();
const title = ref('我的设备')
const searchValue = ref('');
const currentTab = ref('myDevices');
const addPopup = ref();
const emptyStateImage = '';
const OnlineImg = deviceOnlineImg;
const OfflineImg = deviceOfflineImg;
let SelectDeviceId: string | number;
let SelectDeviceName: string;

const deviceList = ref<Array<{
  id: string 
  deviceId: string 
  deviceName: string
  onlineStatus: 1 | 0
  bindStatus: 1 | 0 
  activeTime?: Date
  firmwareVersion?: string
  avatarUrl: string
  deviceType: 1
  voltagePercentage : 0
}>>([])
const loading = ref(false)
const refreshing = ref(false) // 控制刷新状态

const buttons = ref<ButtonItem[]>([
	  {
	    text: '取消',
	    type: 'default',
	    action: () => {
	      console.log('取消按钮点击')
	      return new Promise((resolve) => {
	        setTimeout(() => {
	          resolve(true)
			  handleClose()
	        }, 300)
	      })
	    }
	  },
	  {
	    text: '确认',
	    type: 'primary',
	    action: () => {
	      console.log('确认按钮点击')
	      return new Promise((resolve) => {
			
	        setTimeout(async () => {
				//删除设备
				const result = await confimDelete(SelectDeviceId)
				if(result){
					deviceList.value = deviceList.value.filter(device => device.id !== SelectDeviceId);
					handleClose()
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					});
					await fetchDeviceList()
				}else{
					uni.showToast({
						title: '设备删除失败',
						icon: 'none'
					});
				}
	          resolve(true)
	        }, 300)
	      })
	    }
	  }
	])


// 刷新相关方法
const onRefresh = () => {
  console.log('开始刷新');
  refreshing.value = true;
  fetchDeviceList(true).finally(() => {
    refreshing.value = false;
  });
};
 
const onRestore = () => {
  console.log('刷新恢复');
  // 可以在这里添加一些动画效果
};
 
const onAbort = () => {
  console.log('刷新中断');
  refreshing.value = false;
};

const showPopup = (id:string) => {
	SelectDeviceId = id;
	popupRef.value?.open()
}
	 
const handleClose = () => {
	console.log('弹出层关闭')
	popupRef.value?.close()
}
const handleMaskClick = () => {
	  console.log('点击了遮罩层')
	}
	 
const handleButtonClick = (button: ButtonItem) => {
	  console.log('按钮点击:', button.text)
}

	
//顶部导航栏
const handleBack = () => {
	uni.navigateBack({
		delta:1
	});
};


const openPopup = (id: string ) => {
	SelectDeviceId = id;
	console.log('SelectDeviceId',SelectDeviceId);
	popup.value?.open();
	
};
const  hidePopup = () => {
  if (popup.value) {
    popup.value.close();
  }
}
const popupChange = (e: { show: boolean }) => {
  console.log('弹框状态变化:', e.show);
};
const confirmDeletion = async () => {
  //删除设备
  const result = await confimDelete(SelectDeviceId);
  if(result){
  	deviceList.value = deviceList.value.filter(device => device.id !== SelectDeviceId);
  	uni.showToast({
  		title: '删除成功',
  		icon: 'success'
  	});
  	await fetchDeviceList()
  }else{
  	uni.showToast({
  		title: '设备删除失败',
  		icon: 'none'
  	});
  }
  hidePopup();
}

const handleDelete = (id: string, name: string) => {
	uni.showModal({
		title: '提示',
		content: `确定要注销设备"${name}"吗？`,
		success: async (res) => {
			if (res.confirm) {
				//删除设备
				const result = await confimDelete(id)
				if(result){
					deviceList.value = deviceList.value.filter(device => device.id !== id);
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					});
					await fetchDeviceList()
				}else{
					uni.showToast({
						title: '设备删除失败',
						icon: 'none'
					});
				}
				
			}
		}
	});
};

const navigateToDetail = (deviceId: string ) => {
  uni.navigateTo({
    url: `/pages/deviceDetail/deviceDetail?deviceId=${deviceId}`
  });
};

const switchTab = (tab: string) => {
  uni.switchTab({
    url: `/pages/${tab}/${tab}`
  });
};

const redirectTo = (tab: string) => {
  uni.redirectTo({
    url: `/pages/${tab}/${tab}`
  });
};

const showAddOptions = () => {
  addPopup.value.open();
};

const hideAddOptions = () => {
  addPopup.value.close();
};

const addDevice = () => {
  hideAddOptions();
  uni.navigateTo({
    url: '/pages/blueDevices/blueDevices'
  });
};

const deviceRegister = () => {
  hideAddOptions();
  uni.navigateTo({
    url: '/pages/deviceRegister/deviceRegister'
  });
};

const scanCode = () => {
  hideAddOptions();
  uni.scanCode({
    success: (res) => {
      console.log('扫码结果1：', res);
    }
  });
};

onShow(()=>{
	fetchDeviceList()
})

const fetchDeviceList = async (isRefresh = false) =>{
	try{
		const res = await getDeviceList()
		deviceList.value = res.data||[]
		//refresh
		if(isRefresh){
			//uni.showToast({
			//	title:'刷新成功',
			//	icon:'success',
			//	duration:1500
			//})
		}
	}catch(err){
		console.error('获取设备失败',err)
		//uni.showToast({
		//    title: '刷新失败',
		//    icon: 'none',
		//	duration: 1500
		//});
	}
}
const confimDelete = async (id: string | number) =>{
	if (!id) return
	try{
		return await deleteDevice(id)
	}
	catch(err){
		console.error('删除设备失败',err)
	}
}

</script>



<style >
	page {
		height: 100%;
	}
	.page {
		display: flex;
		flex-direction: column;
		height: 100%;
		background-color: #F8F8F8;
	}
	.search-bar {
		padding: 20rpx 30rpx;
		background-color: #FFFFFF;
		flex-shrink: 0;
	}
	.device-list {
		flex: 1;
		overflow: auto;
	}
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 200rpx;
	}
	.empty-image {
		width: 300rpx;
		height: 300rpx;
		margin-bottom: 30rpx;
	}
	.empty-text {
		font-size: 14px;
		color: #999999;
	}
	.device-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
		padding: 20rpx;
		justify-items: center;
	}
	.device-card {
		background-color: #FFFFFF;
		padding: 30rpx;
		box-shadow: 0rpx 4rpx 10rpx 0rpx rgba(0,0,0,0.3);
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		width: 85%;
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.device-image {
		width: 255rpx;
		height: 204.19rpx;
		margin-bottom: 20rpx;
		object-fit: contain;
	}
	.device-info {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
		width: 100%;
		align-items: center;
		text-align: center;
	}
	.device-version {
		font-size: 12px;
		color: #999999;
	}
	.activated-time {
		font-size: 12px;
		color: #4CD964;
		margin-left: 8rpx;
	}
	.device-name {
		font-size: 16px;
		color: #333333;
		font-weight: 600;
		margin-bottom: 8rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		max-width: 100%;
	}
	.device-status {
		display: flex;
		align-items: center;
		gap: 10rpx;
		flex-wrap: wrap;
		justify-content: space-between;
		
	}
	.status-item {
	  display: flex;
	  align-items: center; /* 确保每个项目内部垂直居中 */
	  flex: 1; /* 使每个项目占据相同空间（可选，根据需求调整） */
	  justify-content: center; /* 项目内元素居中 */
	  margin-right: 10rpx; /* 间距 */
	  margin-left: 10rpx;
	  border-radius: 0rpx 0rpx 0rpx 0rpx;
	}
	.status-dot {
		width: 12rpx;
		height: 12rpx;
		border-radius: 50%;
	}
	.online {
		background-color: #4CD964;
	}
	.offline {
		background-color: #FF3B30;
	}
	.status-text {
		margin-left: 10rpx;
		font-size: 12px;
		color: #999999;
	}
	.tab-bar {
		display: flex;
		justify-content: space-around;
		align-items: center;
		height: 130rpx;
		background-color: #FFFFFF;
		border-top: 1px solid #EEEEEE;
		flex-shrink: 0;
	}
	.tab-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 4rpx;
	}
	.tab-text {
		font-size: 12px;
		color: #666666;
	}
	.tab-text.active {
		color: #007AFF;
	}
	.add-button {
		position: fixed;
		right: 30rpx;
		bottom: 140rpx;
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		background-color: #007AFF;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
	}
	.popup-content {
		background-color: #FFFFFF;
		border-radius: 24rpx 24rpx 0 0;
		padding: 30rpx;
	}
	.popup-title {
		text-align: center;
		font-size: 16px;
		color: #333333;
		font-weight: 500;
		margin-bottom: 30rpx;
	}
	.popup-option {
		display: flex;
		align-items: center;
		gap: 20rpx;
		padding: 30rpx 0;
	}
	.option-text {
		font-size: 16px;
		color: #333333;
	}
	.popup-cancel {
		text-align: center;
		padding: 30rpx 0;
		color: #999999;
		font-size: 16px;
		border-top: 1px solid #EEEEEE;
		margin-top: 20rpx;
	}
	.delete-icon {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	padding: 10rpx;
	}
	.jiantou{
		position: absolute;
		top: 190rpx;
		left: 380rpx;
		width: 125.07rpx;
		height: 87.68rpx;
	}
	.backgroound{
		position: absolute;
		top: 57%;
		right: 12%;
		width: 600rpx;
		height: 250rpx;
		
	}
	.image-container{
		width: 553rpx;
		height: 196.16rpx;
		background-image: url(/static/loading_background1.png);
		background-size: 100% 100%;
		background-position: center;
		border-radius: 10rpx;
		position:absolute;
		top:900rpx;
		left:98rpx;
		padding: 78rpx 100rpx 0 115rpx;
		    line-height: 42rpx;
		    box-sizing: border-box;
	}
	
	.text-overlay {
		line-height: 40rpx;
		margin-top: 7rpx;
		letter-spacing: 0.90%;
		font-family: Source Han Sans,Source Han Sans;
		font-weight: 700;
		font-size: 30rpx;
		color: #FFFFFF;
		font-style: normal;
		text-transform: none
	  
	}
	.text-overlay1 {
	  margin-top: 10rpx;
	  color: #fff;
	  font-size: 30rpx;
	}
	
	/* Loading弹窗样式 (保持不变) */
	.loading-box {
	  width: 750rpx;
	  height: 350rpx;
	  background-image: url(/static/loading_background.png);
	  background-size: 100% 100%;
	  background-position: center;
	  border-radius: 10rpx;
	  display: flex;
	  flex-direction: column;
	  justify-content: center;
	  align-items: center;
	  position: relative;
	}
	.loading-spinner {
	  width: 40rpx;
	  height: 40rpx;
	  border: 4rpx solid rgba(255, 255, 255, 0.3);
	  border-top: 4rpx solid #fff;
	  border-radius: 50%;
	  animation: spin 1s linear infinite;
	}
	
	.loading-text {
	  margin-top: 10rpx;
	  color: #fff;
	  font-size: 32rpx;
	}
	
	.button-group {
	  display: flex;
	  justify-content: space-between;
	  gap: 24rpx;
	  position: absolute;
	  top:255rpx;
	  height: 48rpx;
	}
	.btn {
	  flex: 1;
	  font-size: 34rpx;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	}
	
	.cancel-btn {
	  background-color: #F5F5F5 !important;
	  color: #666666 !important;
	}
	
	.confirm-btn {
	  background: linear-gradient(90deg, #4A90E2 0%, #5C9EFF 100%) !important;
	  color: #FFFFFF !important;
	}
	
	.content {
	  text-align: center;
	  margin-bottom: 48rpx;
	}
	
	.title {
	  font-size: 36rpx;
	  color: #FFFFFF;
	  font-weight: 500;
	  padding: 0rpx 113rpx 0 115rpx;
	      line-height: 43rpx;
	      box-sizing: border-box;
	}
	
	.desc {
	  font-size: 32rpx;
	  color: #FFFFFF;
	  line-height: 2.7;
	}
	.device {
		width: 60rpx;
		height: 60rpx;
	}
	.user {
		width: 60rpx;
		height: 60rpx;
	}
	.refresher {
	    position: relative;
	    width: 100%;
	    height: 100%;
	    display: flex;
	    justify-content: center;
	    align-items: center;
	  }
	  
	  .refresher-loading {
	    position: absolute;
	    top: 10px;
	    left: 50%;
	    transform: translateX(-50%);
	    display: flex;
	    align-items: center;
	    justify-content: center;
	  }
	  
	  .refresher-text {
	    margin-left: 10px;
	    font-size: 14px;
	    color: #666;
	  }
	  .BatteryIcon{
		width: 46rpx;
		height: 28rpx;
	  }
	
</style>
